package dyy.zc.sportruler.utils;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import dyy.zc.sportruler.application.MyApplication;
import dyy.zc.sportruler.bean.PlanInfo;
import dyy.zc.sportruler.bean.SendPlan;
import dyy.zc.sportruler.bean.SportDetail;
import dyy.zc.sportruler.bean.SportName;
import dyy.zc.sportruler.bean.StudentInfo;
import dyy.zc.sportruler.bean.UserInfo;
import dyy.zc.sportruler.constant.Constants;
import dyy.zc.sportruler.ui.activity.ChooseActionActivity;
import dyy.zc.sportruler.ui.activity.EditMyInfoActivity;
import dyy.zc.sportruler.ui.activity.LoginActivity;
import dyy.zc.sportruler.ui.activity.MakePlanActivity;
import dyy.zc.sportruler.ui.activity.RegisterActivity;
import dyy.zc.sportruler.ui.activity.SettingActivity;

/**
 * Created by chuan on 2017/4/11.
 */

public class BmobUtils {
    private Context context;
    public static boolean userHead = false;
    public static boolean loginSuccess = false;
    private boolean registerSuccess = true;
    public static boolean isFirst = true;
    public static List<SportName> list_sportName = new ArrayList<SportName>();
    public static List<SportDetail> list_sportDetail = new ArrayList<SportDetail>();

    public BmobUtils(Context context) {
        this.context = context;
    }

    /**
     * 获取所有的学员信息
     * @param resultCode
     * @param failedCode
     * @param handler
     */
    public void getAllStudentInfo(final int resultCode, final int failedCode, final Handler handler){
        BmobQuery<StudentInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<StudentInfo>() {
            @Override
            public void done(List<StudentInfo> list, BmobException e) {
                if (e == null){
                    Log.e("getAllStudentInfo","ok");
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) list);
                    message.setData(bundle);
                    message.what = resultCode;
                    handler.sendMessage(message);
                }else {
                    handler.sendEmptyMessage(failedCode);
                    Log.e("getAllStudentInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 获取所有的健身计划
     * @param resultCode
     * @param handler
     */
    public void getAllPlanInfo(final int resultCode, final int failedCode, final Handler handler){
        BmobQuery<PlanInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<PlanInfo>() {
            @Override
            public void done(List<PlanInfo> list, BmobException e) {
                if (e == null){
                    Log.e("getAllPlanInfo","ok");
                    Message message = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("list", (Serializable) list);
                    message.setData(bundle);
                    message.what = resultCode;
                    handler.sendMessage(message);
                }else {
                    handler.sendEmptyMessage(failedCode);
                    Log.e("getAllPlanInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 保存学员信息
     * @param studentInfo
     * @param resultCode
     * @param handler
     */
    public void saveStudentInfo(StudentInfo studentInfo,final int resultCode, final Handler handler){
        studentInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    Log.e("saveStudentInfo","ok");

                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("saveStudentInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 保存发送的计划
     * @param sendPlan
     * @param resultCode
     * @param handler
     */
    public void saveSendPlan(SendPlan sendPlan,final int resultCode, final Handler handler){
        sendPlan.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    Log.e("saveStudentInfo","ok");
                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("saveStudentInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 保存计划
     * @param planInfo
     * @param resultCode
     * @param handler
     */
    public void savePlan(PlanInfo planInfo,final int resultCode, final Handler handler){
        planInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null){
                    Log.e("savePlan","ok "+s);
                    ((MakePlanActivity)context).studentInfo.setId(s);
                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("savePlan",e.getMessage());
                }
            }
        });
    }

    /**
     * 获取计划
     */
    public void getPlanInfo(final List<PlanInfo> planInfoList, String id,String name, final int resultCode, final Handler handler){
        BmobQuery<PlanInfo> query = new BmobQuery<>();
        query.addWhereEqualTo("id",id);
        query.addWhereEqualTo("studentName",name);
        query.findObjects(new FindListener<PlanInfo>() {
            @Override
            public void done(List<PlanInfo> list, BmobException e) {
                if (e == null){
                    Log.e("getPlanInfo","ok ");
                    planInfoList.clear();
                    planInfoList.addAll(list);
                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("getPlanInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 获取计划
     */
    public void getPlanInfo(final List<PlanInfo> planInfoList, String id, final int resultCode, final Handler handler){
        BmobQuery<PlanInfo> query = new BmobQuery<>();
        query.addWhereEqualTo("objectId",id);
        query.findObjects(new FindListener<PlanInfo>() {
            @Override
            public void done(List<PlanInfo> list, BmobException e) {
                if (e == null){
                    Log.e("getPlanInfo","ok ");
                    planInfoList.clear();
                    planInfoList.addAll(list);
                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("getPlanInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 获取发送过的计划
     */
    public void getSendPlanInfo(final List<SendPlan> sendPlanList, String id, final int resultCode, final Handler handler){
        BmobQuery<SendPlan> query = new BmobQuery<>();
        query.addWhereEqualTo("id",id);
        query.findObjects(new FindListener<SendPlan>() {
            @Override
            public void done(List<SendPlan> list, BmobException e) {
                if (e == null){
                    Log.e("getSendPlanInfo","ok");
                    sendPlanList.clear();
                    sendPlanList.addAll(list);
                    handler.sendEmptyMessage(resultCode);
                }else {
                    Log.e("getSendPlanInfo",e.getMessage());
                }
            }
        });
    }


    /**
     * 筛选动作SportName
     *
     * @param sportNameList
     * @param key
     * @param value
     * @param resultCode
     * @param handler
     */
    public void classifySportName(final List<SportName> sportNameList, String[] key, String[] value, final int resultCode, final Handler handler) {
        BmobQuery<SportName> query = new BmobQuery<>();
        for (int i = 0; i < key.length; i++) {
            if (value[i].equals("")) {
                query.addWhereNotEqualTo(key[i], value[i]);
            } else {
                query.addWhereEqualTo(key[i], value[i]);
            }
        }
        query.findObjects(new FindListener<SportName>() {
            @Override
            public void done(List<SportName> list, BmobException e) {
                if (e == null) {
                    Log.e("classifySportName", "ok");
                    sportNameList.clear();
                    sportNameList.addAll(list);
                    handler.sendEmptyMessage(resultCode);
                } else {
                    Log.e("classifySportName", "ok");
                }
            }
        });
    }



    /**
     * 更新User信息--设置专用
     *
     * @param userInfo
     */
    public void updateUser(UserInfo userInfo) {
        userInfo.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateUserInfo", "ok");
                    ((SettingActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    ((SettingActivity) context).handler.sendEmptyMessage(456);
                    e.printStackTrace();
                    Log.e("updateUserInfo", "failed");
                }
            }
        });
    }
    /**
     * 编辑个人信息时的上传图片---设置专用
     *
     * @param bmobFile
     * @param loginuser
     */
    public void upLoadHeadFile(final BmobFile bmobFile, final UserInfo loginuser) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    userHead = true;
                    loginuser.setHead(bmobFile);//设置头像
                    ((SettingActivity) context).handler.sendEmptyMessage(Constants.ResultCode.UPLOAD_SUCCESS);
                    Log.e("upLoadUserHeadFile", "ok");
                } else {
                    ((EditMyInfoActivity) context).handler.sendEmptyMessage(Constants.ResultCode.FAILED);
                    Log.e("upLoadUserHeadFile", e.getMessage());
                }
            }
        });
    }
    /**
     * 筛选动作
     *
     * @param sportDetails
     * @param key
     * @param value
     * @param resultCode
     * @param handler
     */
    public void classifySportDetail(final List<SportDetail> sportDetails, String key, String value, final int resultCode, final Handler handler) {
        BmobQuery<SportDetail> query = new BmobQuery<>();
        query.addWhereEqualTo(key, value);
        query.findObjects(new FindListener<SportDetail>() {
            @Override
            public void done(List<SportDetail> list, BmobException e) {
                if (e == null) {
                    Log.e("classifySportName", "ok");
                    sportDetails.clear();
                    sportDetails.addAll(list);
                    handler.sendEmptyMessage(resultCode);
                } else {
                    Log.e("classifySportName", "ok");
                }
            }
        });
    }

    /**
     * 初始化动作细节
     */
    public void initSportDetailData() {
        BmobQuery<SportDetail> query = new BmobQuery<SportDetail>();
        query.findObjects(new FindListener<SportDetail>() {
            @Override
            public void done(List<SportDetail> list, BmobException e) {
                if (e == null) {
                    list_sportDetail.clear();
                    list_sportDetail.addAll(list);
                    ((ChooseActionActivity) context).handler.sendEmptyMessage(1);
                } else {
                    Toast.makeText(context, "获取失败，请返回重新获取", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 初始化动作名字
     */
    public void initSportNameData() {
        BmobQuery<SportName> query = new BmobQuery<SportName>();
        query.findObjects(new FindListener<SportName>() {
            @Override
            public void done(List<SportName> list, BmobException e) {
                if (e == null) {
                    list_sportName.clear();
                    list_sportName.addAll(list);
                    ((ChooseActionActivity) context).handler.sendEmptyMessage(1);
                } else {
                    Toast.makeText(context, "获取失败，请返回重新获取", Toast.LENGTH_SHORT).show();
                }


            }
        });
    }

    /**
     * 登录查询是否账号密码输入错误
     */
    public void queryAccount(final UserInfo account) {
        BmobQuery<UserInfo> bmobQuery = new BmobQuery<>();
        bmobQuery.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("queryAccount", "ok");
                    for (UserInfo a :
                            list) {
                        if (a.getAccount().equals(account.getAccount()) && a.getPassword().equals(account.getPassword())) {
                            loginSuccess = true;
                            MyApplication.getInstance().saveUserInfo(a);
                            break;
                        }
                    }
                } else {
                    e.printStackTrace();
                    Log.e("queryAccount", "Failed");
                }
                ((LoginActivity) context).handler.sendEmptyMessage(Constants.ResultCode.RESULT_SUCCESS);
            }
        });
    }

    /**
     * 找回密码
     */
    public void getBackYourAccount(final String phone, final String userPassword) {
        final BmobQuery<UserInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("getBackYourAccount", "ok");
                    for (UserInfo a :
                            list) {
                        if (a.getAccount().equals(phone)) {
                            a.setPassword(userPassword);
                            findPassword(a);
                            break;
                        }
                    }
                } else {
                    Log.e("getBackYourAccount", e.getMessage());
                }
            }
        });
    }

    /**
     * 更新用户密码
     *
     * @param account
     */
    public void findPassword(UserInfo account) {
        account.update(account.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateAccountInfo", "ok");
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("updateAccountInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传图片文件--注册时默认的用户头像
     *
     * @param bmobFile
     * @param account
     */
    public void upMoRenFile(final BmobFile bmobFile, final UserInfo account) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    account.setHead(bmobFile);
                    addUserInfo(account);
                    Log.e("upLoadFile", "ok--" + bmobFile.getFileUrl());
                } else {
                    e.printStackTrace();
                    Log.e("upLoadFile", e.getMessage());
                }
            }
        });
    }

    /**
     * 增加用户
     *
     * @param account
     */
    public void addUserInfo(final UserInfo account) {
        account.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("Bmob-addUserInfo", "ok");
                    ((RegisterActivity) context).account.setId(s);
                    updateInfo(((RegisterActivity) context).account);
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    Log.e("Bmob-addUserInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 注册新用户验证
     *
     * @param userPhone 账号
     */
    public void registerChecked(final String userPhone) {
        BmobQuery<UserInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("list", list + "");
                    Log.e("registerChecked", "ok");
                    for (UserInfo a :
                            list) {
                        if (a.getAccount().equals(userPhone)) {
                            registerSuccess = false;
                            break;
                        }
                    }
                    if (!registerSuccess) {
                        ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_FAILED);
                    } else {
                        ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_SUCCESS);
                    }
                } else {
                    Log.e("registerChecked", e.getMessage());
                }

            }
        });
    }


    /**
     * 更新用户信息
     *
     * @param userInfo
     */
    public void updateInfo(UserInfo userInfo) {
        userInfo.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateInfo", "ok");
                } else {
                    Log.e("updateInfo", e.getMessage());
                }
            }
        });
    }

    public void updateInfo(UserInfo userInfo, final int resultCode, final Handler handler){
        userInfo.update(userInfo.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateInfo", "ok");
                    handler.sendEmptyMessage(resultCode);
                } else {
                    Log.e("updateInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 更新User信息--新用户编辑信息
     *
     * @param userInfo
     */
    public void updateFirstInfo(UserInfo userInfo) {
        userInfo.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateFirstInfo", "ok");
                    ((EditMyInfoActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    ((EditMyInfoActivity) context).handler.sendEmptyMessage(456);
                    e.printStackTrace();
                    Log.e("updateFirstInfo", "failed");
                }
            }
        });
    }

    /**
     * 开始编辑个人信息时的上传图片
     *
     * @param bmobFile
     * @param loginuser
     */
    public void upLoadUserHeadFile(final BmobFile bmobFile, final UserInfo loginuser) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    userHead = true;
                    loginuser.setHead(bmobFile);//设置头像
                    ((EditMyInfoActivity) context).handler.sendEmptyMessage(Constants.ResultCode.UPLOAD_SUCCESS);
                    //updateUserInfo(loginuser);//更新用户信息
                    Log.e("upLoadUserHeadFile", "ok");
                } else {
                    ((EditMyInfoActivity) context).handler.sendEmptyMessage(Constants.ResultCode.FAILED);
                    Log.e("upLoadUserHeadFile", e.getMessage());
                }
            }
        });
    }

    public void uploadCodeImg(final BmobFile bmobFile, final int resultCode, final int failedCode, final Handler handler){
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("upLoadFile", "ok");
                    ((MakePlanActivity) context).sendPlan.setImg(bmobFile);
                    handler.sendEmptyMessage(resultCode);
                } else {
                    Log.e("upLoadFile", e.getMessage());
                    handler.sendEmptyMessage(failedCode);
                }
            }
        });
    }

    /**
     * 上传图片
     *
     * @param bmobFile
     * @param resultCode
     * @param failedCode
     * @param handler
     */
    public void upLoadFile(final BmobFile bmobFile, final int resultCode, final int failedCode, final Handler handler) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("upLoadFile", "ok");
                    Message message = new Message();
                    message.what = resultCode;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("file", bmobFile);
                    message.setData(bundle);
                    handler.sendMessage(message);
                } else {
                    Log.e("upLoadFile", e.getMessage());
                    handler.sendEmptyMessage(failedCode);
                }
            }
        });
    }

    /**
     * 获取学员列表
     * @param studentInfos
     * @param resultCode
     * @param failedCode
     * @param handler
     */
    public void getStudentInfo(final List<StudentInfo> studentInfos,String id, final int resultCode, final int failedCode, final Handler handler){
        BmobQuery<StudentInfo> query = new BmobQuery<>();
        query.addWhereEqualTo("teacherID",id);
        query.findObjects(new FindListener<StudentInfo>() {
            @Override
            public void done(List<StudentInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("getStudentInfo", "ok");
                    studentInfos.clear();
                    studentInfos.addAll(list);
                    handler.sendEmptyMessage(resultCode);
                } else {
                    Log.e("getStudentInfo", e.getMessage());
                    handler.sendEmptyMessage(failedCode);
                }
            }
        });
    }

    /**
     * 筛选搜索学员
     * @param studentInfos
     * @param id
     * @param value
     * @param resultCode
     * @param failedCode
     * @param handler
     */
    public void classifyStudent(final List<StudentInfo> studentInfos,String id,String value, final int resultCode, final int failedCode, final Handler handler){
        BmobQuery<StudentInfo> query = new BmobQuery<>();
        query.addWhereEqualTo("teacherID",id);
        if (value.equals("")){
            query.addWhereNotEqualTo("name",value);
        }else {
            query.addWhereEqualTo("name",value);
        }

        query.findObjects(new FindListener<StudentInfo>() {
            @Override
            public void done(List<StudentInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("classifyStudent", "ok");
                    studentInfos.clear();
                    studentInfos.addAll(list);
                    handler.sendEmptyMessage(resultCode);
                } else {
                    Log.e("classifyStudent", e.getMessage());
                    handler.sendEmptyMessage(failedCode);
                }
            }
        });
    }
}